<template>
    <Modal :mask-closable="false" v-model="showModal" :title="inject.edit ? '编辑':'新增'" @on-ok="ok" @on-cancel="cancel" :loading="modalLoading" class="add-edit-music-type-modal">
        <Form ref="typeEditForm" :model="typeEditForm" :rules="typeEditFormRule" :label-width="80">
            <Row>
                <Col span="6">
                    <header-img-uploader :img-upload-path="imgUploadPath" :upload-img-data="uploadImgdata" @on-upload-success="uploadSuccess" :show-img-path="uploadCallbackPath"></header-img-uploader>
                </Col>
                <Col span="18">
                    <FormItem prop="type_name" label="目录名称">
                        <Input v-model="typeEditForm.type_name" placeholder="输入目录名称"></Input>
                    </FormItem>
                    <FormItem prop="type_code" label="类型编号">
                        <Input v-model="typeEditForm.type_code" placeholder="输入目录名称的首字母"></Input>
                    </FormItem>
                </Col>
            </Row>
            <FormItem style="padding-left:65px">
                <CheckboxGroup >
                    <Checkbox label="推荐在APP首页" v-model="typeEditForm.recommend_flag"></Checkbox>
                    <Checkbox label="专辑"  v-model="typeEditForm.is_album"></Checkbox>
                    <Checkbox label="叶子节点"  v-model="typeEditForm.leaf_flag"></Checkbox>
                </CheckboxGroup>
                <span style="color:#999">叶子节点：勾选，即这个目录下没有子目录</span>
            </FormItem>
            <FormItem label="专辑售价" v-if="typeEditForm.is_album">
                 <InputNumber :min="0" :step="1"  :precision="2" v-model="typeEditForm.sale_price"></InputNumber>
            </FormItem>
            <FormItem label="类型描述" prop="description">
                <Input v-model="typeEditForm.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入描述，最多100字" :maxlength="100"></Input>
            </FormItem>
        </Form>
    </Modal>
</template>
<script>
import headerImgUploader from "../../Components/headerImgUploader.vue";
import validate from '../../../libs/validate.js';

export default {
  name: "addEditModal",
  components: {
    headerImgUploader
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    inject: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  data() {
    // const validateRoleName = (rule, value, callback) => {
    //   if (value === "" || value.replace(/(^\s*)|(\s*$)/g, "") === "") {
    //     callback(new Error("不能为空,请正确填写"));
    //   } else {
    //     callback();
    //   }
    // };
    // const validateRoleNameCode = (rule, value, callback) => {
    //   if (value === "" || value.replace(/(^\s*)|(\s*$)/g, "") === "") {
    //     callback(new Error("不能为空,请正确填写"));
    //   } else {
    //     if (/^[A-Za-z]+$/.test(value)) {
    //       callback();
    //     } else {
    //       callback(new Error("只允许填写英文"));
    //     }
    //   }
    // };
    return {
      typeEditForm: {
        type_name: "",
        type_code: "",
        leaf_flag: false,
        is_album: false,
        recommend_flag: false,
        description: "",
        sale_price: 0
      },
      typeEditFormRule: {
        type_name: [
          {
            required: true,
            validator: validate.name,
            trigger: "blur"
          }
        ],
        type_code: [
          {
            required: true,
            validator: validate.enOnly,
            trigger: "blur"
          }
        ],
        description: [
          {
            required: true,
            validator: validate.name,
            trigger: "blur"
          }
        ]
      },
      showModal: false,
      modalLoading: true,
      imgUploadPath: "",
      isUploading: false,
      uploadProgress: 0,
      uploadImgdata: {},
      uploadCallbackPath: ""
    };
  },
  computed: {
    user() {
      return this.$store.state.user.data;
    }
  },
  methods: {
    ok() {
      if (this.inject.edit) {
        this.submitChange();
        return;
      }
      this.submitNew();
    },
    cancel() {},
    changeLoadingStatus(type) {
      if (!type) {
        this.modalLoading = false;
      }
      this.$nextTick(() => {
        this.modalLoading = true;
      });
    },
    submitNew() {
      if (!this.uploadCallbackPath) {
        this.$Notice.error({
          title: "请先上传图片后再操作"
        });
        this.changeLoadingStatus(false);
        return;
      }
      this.$refs.typeEditForm.validate(valid => {
        if (valid) {
          this.changeLoadingStatus(true);
          this.http
            .post(this.postUrl.addNewMusicType, {
              token: this.user.tokenList[0],
              parent_uuid: this.inject.uuid ? this.inject.uuid : "xpqh",
              type_name: this.typeEditForm.type_name,
              type_code: this.typeEditForm.type_code,
              depth: this.inject.depth ? "2" : "1",
              path: this.inject.path
                ? this.inject.path + "/" + this.typeEditForm.type_code
                : "xpqh/" + this.typeEditForm.type_code,
              orders: 1,
              icon_url: this.uploadCallbackPath,
              recommend_flag: this.typeEditForm.recommend_flag ? "1" : "0",
              leaf_flag: this.typeEditForm.leaf_flag ? "1" : "0",
              is_album: this.typeEditForm.is_album ? "1" : "0",
              sale_price: this.typeEditForm.sale_price,
              description: this.typeEditForm.description
            })
            .then(
              data => {
                if (data.code > -1) {
                  this.$emit("on-add-success", data.data);
                  this.showModal = false;
                } else {
                  this.errorHandle(data.msg);
                }
                this.changeLoadingStatus(false);
              },
              () => {
                this.errorHandle();
                this.changeLoadingStatus(false);
              }
            );
        } else {
          this.changeLoadingStatus(false);
        }
      });
    },
    submitChange() {
      if (!this.uploadCallbackPath) {
        this.$Notice.error({
          title: "请先上传图片后再操作"
        });
        this.changeLoadingStatus(false);
        return;
      }
      this.$refs.typeEditForm.validate(valid => {
        if (valid) {
          this.changeLoadingStatus(true);
          let path = this.inject.path.split("/");
          path.splice(-1, 1);
          this.http
            .post(this.postUrl.changeMusicTypeInfo, {
              token: this.user.tokenList[0],
              uuid: this.inject.uuid,
              type_name: this.typeEditForm.type_name,
              type_code: this.typeEditForm.type_code,
              depth: this.inject.depth,
              path: path.join("/") + "/" + this.typeEditForm.type_code,
              orders: 1,
              icon_url: this.uploadCallbackPath,
              recommend_flag: this.typeEditForm.recommend_flag ? "1" : "0",
              leaf_flag: this.typeEditForm.leaf_flag ? "1" : "0",
              is_album: this.typeEditForm.is_album ? "1" : "0",
              sale_price: this.typeEditForm.sale_price,
              description: this.typeEditForm.description
            })
            .then(
              data => {
                if (data.code > -1) {
                  this.$emit("on-add-success", data.data);
                  this.showModal = false;
                } else {
                  this.errorHandle(data.msg);
                }
                this.changeLoadingStatus(false);
              },
              () => {
                this.errorHandle();
                this.changeLoadingStatus(false);
              }
            );
        } else {
          this.changeLoadingStatus(false);
        }
      });
    },
    uploadSuccess(data) {
      this.uploadCallbackPath = data;
    },
    getDetail(uuid) {
      this.uploadCallbackPath = this.inject.icon_url;
      this.typeEditForm = {
        type_name: this.inject.type_name,
        type_code: this.inject.type_code,
        leaf_flag: this.inject.leaf_flag == "1" ? true : false,
        is_album: this.inject.is_album == "1" ? true : false,
        recommend_flag: this.inject.recommend_flag == "1" ? true : false,
        sale_price: this.inject.sale_price ? this.inject.sale_price : 0
      };
      return new Promise((resolve, reject) => {
        this.http
          .post(this.postUrl.getMusicTypeDetail, {
            token: this.user.tokenList[0],
            uuid: uuid
          })
          .then(
            data => {
              if (data.code > -1) {
                this.$set(
                  this.typeEditForm,
                  "description",
                  data.data.description
                );
                //   this.typeEditForm.description = data.data.description;
              } else {
                this.showModal = false;
                this.errorHandle(data.msg);
              }
            },
            () => {
              this.showModal = false;
              this.errorHandle();
            }
          );
      });
    }
  },
  mounted() {
    this.imgUploadPath = this.postUrl.uploadMusicTypeImg;
    setTimeout(() => {
      let body = {
        token: this.user.tokenList[0],
        app_key: this.http.app_key,
        timestamp: "2017-09-26 15:52:28"
      };
      let sign = this.http.getSign({
        token: this.user.tokenList[0]
      });
      body.sign = sign;
      this.uploadImgdata = body;
    }, 200);
  },
  watch: {
    value(val) {
      if (this.showModal != val) {
        this.showModal = val;
      }
      if (val) {
        if (this.inject.edit) {
          setTimeout(() => {
            this.getDetail(this.inject.uuid);
          }, 200);
        }
      }
    },
    showModal(val) {
      if (val !== this.value) {
        this.$emit("input", val);
        setTimeout(() => {
          this.uploadCallbackPath = "";
          this.typeEditForm = {
            type_name: "",
            type_code: "",
            leaf_flag: false,
            is_album: false,
            recommend_flag: false,
            description: "",
            sale_price: 0
          };
        }, 300);
      }
    }
  }
};
</script>
<style lang="scss">

</style>